YAHOO.namespace("pingmob");
YAHOO.namespace("pingmob.container");

YAHOO.util.Event.onDOMReady(function () {
    YAHOO.pingmob.userList = function () {

        try {
            var number_per_page_default = 10;

            var Dom = YAHOO.util.Dom,
                Event = YAHOO.util.Event;

            var myPaginator = new YAHOO.widget.Paginator({
                containers: ['txs-thread-paging', 'txs-thread-paging_top'],
                rowsPerPage: number_per_page_default,
                previousPageLinkClass: "yui-pg-previous gc-inbox-prev",
                nextPageLinkClass: "yui-pg-next gc-inbox-next"//,
                //template           : "<strong>{CurrentPageReport}</strong> {PreviousPageLink} {NextPageLink}",
                //pageReportTemplate : "{startIndex}-{endIndex} of {totalRecords}"
            });

            var myTableConfig = {
                paginator: myPaginator,
                MSG_EMPTY: messages["js.no.records.found"],
                dynamicData: true,
                initialLoad: false,
                width: '100%'
            };

            var formatDate = function (elCell, oRecord, oColumn, oData) {
                if (oData != null && oData != "") {
                    var oDate = new Date(oData);
                    elCell.innerHTML = YAHOO.util.Date.format(oDate, {format: "%Y-%m-%d"});
                }
            };

            var myColumnDefs = [
                //{key:"Select", label:"", formatter:"checkbox", className:"table-checkbox"},
                {key: "orderId", label: "交易号", sortable: false},
                {key: "productId", label: "问题号", sortable: true},
                {key: "dateAdded", label: '消费时间', sortable: true},
                {key: "costOzingPoint", label: '消费金额', sortable: true},
                {key: "orderStatus", label: '当前状态', sortable: false, formatter:function (elCell, oRecord) {
                    if (oRecord.getData('orderStatus') == 'OrderStatusType_CONFIRM') {
                        elCell.innerHTML = "已确认";
                    } else if (oRecord.getData('orderStatus') == 'OrderStatusType_CANCEL') {
                        elCell.innerHTML = "已取消";
                    } else if (oRecord.getData('orderStatus') == 'OrderStatusType_NEW') {
                        elCell.innerHTML = "新建";
                    } else {
                        elCell.innerHTML = "其它";
                    }
                }},
                {key: "orderType", label: '问题类型', sortable: false, formatter:function (elCell, oRecord) {
                    if (oRecord.getData('orderType') == 'OFFLINEQA') {
                        elCell.innerHTML = "离线答疑";
                    } else if (oRecord.getData('orderType') == 'ONLINEQA') {
                        elCell.innerHTML = "在线答疑";
                    } else {
                        elCell.innerHTML = "其它";
                    }
                }},
                {key:"productDesc", label:'消费描述',sortable:false},
                {key: "createdBy", label: "登录名(username)", sortable: false},
                {key: "firstName", label: "用户名", sortable: false},
                {key: "deviceInfo", label: "设备号", sortable: false}
                /*,
           {key:"txType", label:'消费类型',sortable:true}
           {key:"view", label:'星卡详情', className:"table-action", action:'view', formatter:function (elCell) {
               elCell.innerHTML = '<img src="/static/images/edit.gif" title="查看"/>';
               elCell.style.cursor = 'pointer';
           }},
           {key:"oauth", label:'Oauth', className:"table-action", action:'oauth', formatter:function (elCell) {
               elCell.innerHTML = '<img src="/static/images/edit.gif" title="Oauth授权"/>';
               elCell.style.cursor = 'pointer';
           }}*/
            ];

            var

                txsDataSource = new YAHOO.util.DataSource('/ozing/vipOrder/json?'
                );
            txsDataSource.responseType = YAHOO.util.DataSource
                .TYPE_JSON;
            txsDataSource.responseSchema = {
                resultsList:'records',
                metaFields:{
                    totalRecords: 'totalRecords',
                    paginationRecordOffset: "startIndex",
                    paginationRowsPerPage: "pageSize",
                    sortKey: "sort",
                    sortDir: "dir"
                }
            };

            var txsDataTable = new YAHOO.widget.DataTable("txs-thread-list", myColumnDefs,

                txsDataSource, myTableConfig);
            // Show loading message while page is being rendered
            txsDataTable.showTableMessage(txsDataTable.get("MSG_LOADING"),

                YAHOO.widget.DataTable.CLASS_LOADING);
            // Add the instances to the YAHOO.example namespace for inspection
            YAHOO.pingmob.BHMIntegration_files
                ={
                myPaginator  :myPaginator,
                txsDataSource : txsDataSource,
                txsDataTable  : txsDataTable
            };

            // Integrate with Browser History Manager
            var History = YAHOO.util.History;
            // Define a custom function to route sorting through the Browser History Manager
            var handleSorting = function (oColumn) {

                // Calculate next sort direction for given Column
                var sDir = this.
                    getColumnSortDir(oColumn);
                // The next state will reflect the new sort values
                // while preserving existing pagination rows-per-page
                // As a best practice, a new sort will reset to page 0

                var newState = generateRequest(0, oColumn.key, sDir, this.get(
                    "paginator").getRowsPerPage());
                // Pass the state along to the Browser History Manager
                History.navigate("txTable", newState);
            };
            txsDataTable.sortColumn =
                handleSorting;
            // Define a custom function to route pagination through the Browser History Manager
            var handlePagination = function (state) {
                // The next state will reflect the new pagination values
                // while preserving existing sort values
                // Note that the sort direction needs to be converted from DataTable format to server value
                var sortedBy  = this.get("sortedBy"),
                    newState =

                        generateRequest(
                        state.recordOffset,
                            sortedBy.key, sortedBy.dir, state.

                                rowsPerPage
                    );
                // Pass the state along to the Browser History Manager
                History.navigate("txTable", newState);
            };
            // First we must unhook the built-in mechanism...
            myPaginator.unsubscribe("changeRequest", txsDataTable.

                onPaginatorChangeRequest);
            // ...then we hook up our custom function
            myPaginator.subscribe("changeRequest", handlePagination, txsDataTable,
                true);
            // Update totalRecords on the fly with values from server
            txsDataTable.
                doBeforeLoadData = function (oRequest, oResponse, oPayload) {
                var meta = oResponse.meta;
                oPayload.totalRecords = meta.totalRecords || oPayload.
                    totalRecords
                ;
                oPayload.pagination = { rowsPerPage:meta.paginationRowsPerPage ||
                    number_per_page_default,
                    recordOffset:meta.paginationRecordOffset || 0
                };
                if(oPayload.totalRecords==undefined){
                    oPayload.totalRecords=0;
                }
                oPayload.sortedBy = {

                    key: meta.sortKey || "dateAdded",
                    dir: (meta.sortDir) ? "yui-dt-" + meta.
                        sortDir : "yui-dt-asc"
                    // Convert from server value to DataTable format
                };
                return true;
            };

            var generateRequest = function (startIndex,sortKey,dir,results) {
                var username = encodeURIComponent(Dom.get("username").value);
                var nickname = encodeURIComponent(Dom.get("nickname").value);
                var deviceNumber = encodeURIComponent(Dom.get("deviceNumber").value);
                var agent = encodeURIComponent(Dom.get("agent").value);
                var productId = encodeURIComponent(Dom.get("productId").value);
                var startDate = encodeURIComponent(Dom.get("startDate").value);
                var endDate =
                    encodeURIComponent(Dom.get("endDate").value);
                startIndex = startIndex || 0;
                sortKey = sortKey || "dateAdded";
                dir = (dir) ? dir.substring(7) : "desc"; // Converts from DataTable format "yui-dt-[dir]" to server value "[dir]"
                results = results ||

                    number_per_page_default;
                return  "sort=" + sortKey + "&dir=" +
                    dir + "&start_index=" + startIndex + "&num_per_page=" +
                    results  +
                    "&username=" + username + "&deviceNumber=" + deviceNumber + "&agent=" + agent + "&productId=" + productId + "&nickname=" + nickname +
                    "&startDate=" + startDate + "&endDate=" + endDate + "&date=" + new Date().getTime();
            };
            // Called by Browser History Manager to trigger a new state
            var handleHistoryNavigation =
                function (request) {
                //show the "loading" message.
                txsDataTable.getTbodyEl().
                    style.display = "none";
                txsDataTable
                    .showTableMessage(messages[
                        "js.loading"]);
                    // Sends a new request to the DataSource
                txsDataSource.sendRequest(request
                    , {
                    success:function () {
                        //checkUsersAll_btn.set("checked", false); //uncheck all.
                        txsDataTable.getTbodyEl().style.display = "";
                        txsDataTable.hideTableMessage();
                        txsDataTable.
                            onDataReturnSetRows.apply(this, arguments);
                    },
                    failure:function () {
                        //checkUsersAll_btn.set("checked", false); //uncheck all.
                        txsDataTable.getTbodyEl().style.
                            display = "";
                        txsDataTable.hideTableMessage(YAHOO.widget.DataTable
                            .MSG_ERROR);

                        txsDataTable.onDataReturnSetRows.apply(this,
                            arguments);
                    },
                    scope:txsDataTable,
                    argument:{}
                        // Pass in container for population at runtime via doBeforeLoadData
                });
            };

            // Calculate the first request
            var initialRequest = History.getBookmarkedState("txTable") ||
                // Passed in via URL
                generateRequest();

            // Get default values
            // Register the module
            History.register("txTable", initialRequest,
                handleHistoryNavigation);
            // Render the first view

            History.onReady(function () {
                // Current state after BHM is initialized is the source of truth for what state to render
                var currentState = History.getCurrentState("txTable");
                handleHistoryNavigation(currentState);
            });

            var renderPage = function () {
                var currentState = History.getCurrentState(
                    "txTable") || generateRequest();
                handleHistoryNavigation(currentState);
            }
                ;

            var searchPage =
                function () {
                var currentState =  generateRequest();
                    handleHistoryNavigation(currentState);
            };
            // Initialize the Browser History Manager.
            YAHOO.util.History.initialize
                ("yui-history-field", "yui-history-iframe");

            txsDataTable.
                subscribe('cellClickEvent', function (ev) {
                var target = YAHOO.util.Event.getTarget(ev);
                var
                    column = this.getColumn

                        (target);
                var record = this.
                    getRecord(
                        target);

                    /*if (column.action == 'view') {
                       //show user cards info.
                       window.location.href = "/admin/ozing/user/cards?id=" + record.getData("id");
                   }else if(column.action=="oauth"){
                        window.open ('/admin/user/token?id=' + record.getData("id"),
                               '生成用户OauthToken','height=320,width=480,top=0,left=0,toolbar=no,menubar=no,scrollbars=yes, resizable=yes,location=no, status=no');
                   }*/
            });

            var refreshTxThread = function (p_oEvent) {
                searchPage();
            };

            //button.
            var refreshTxsThread_btn = new YAHOO.widget.Button("refreshTxsThread",
                { onclick:{ fn:refreshTxThread
                } });
            //var checkUsersAll_btn = new YAHOO.widget.Button("selectTxsAll", { label:messages["select.all"], checked:false });
            var query_btn = new YAHOO.widget.Button(

                "query_txs_btn", {label:messages[
                    "button.search"],onclick:{ fn:searchPage } });

            txsDataTable.subscribe('checkboxClickEvent', function
                (oArgs) {
                var
                    currentPageUrl = History.
                        getCurrentState("txTable")||
                        generateRequest();
                var
                    start_index = parseInt(getRequestValueFromURL(
                        currentPageUrl,
                        "start_index"));
                var elCheckbox = oArgs.
                    target;
                var
                    newValue = elCheckbox.checked;
                var record = this.getRecord(
                    elCheckbox);
                var column = this.
                    getColumn(
                        elCheckbox);
                record.setData(
                    column.key, newValue);

                var

                    allChecked = true;
                var oRS = txsDataTable.
                    getRecordSet();
                for (var i = start_index; i < oRS.getLength();
                     i++) {
                    var oRec = oRS.getRecord(i);
                    if (!oRec.
                        getData('Select')) {
                        allChecked = false;
                        break;
                    }
                }
                //checkUsersAll_btn.set("checked", allChecked);
                if (newValue) {
                    this.selectRow(record);
                } else {
                    this.unselectRow(
                        record);
                }
                if (txsDataTable.
                    getSelectedRows().length > 0) {
                    //tokenUsersThread_btn.set("disabled", false);
                } else {
                    //tokenUsersThread_btn.set("disabled", true);
                }
                return false;
            });
            /*checkUsersAll_btn.on("click", function (e) {
                var currentPageUrl = History.getCurrentState("txTable")||generateRequest();
                var start_index = parseInt(getRequestValueFromURL(currentPageUrl, "start_index"));
                var check = checkUsersAll_btn.get("checked");
                var oRS = txsDataTable.getRecordSet();
                for (var i = start_index; i < oRS.getLength(); i++) {
                    var oRec = oRS.getRecord(i);
                    oRec.setData('Select', check);
                    if (check) {
                        txsDataTable.selectRow(oRec);
                    } else {
                        txsDataTable.unselectRow(oRec);
                    }
                }
                txsDataTable.render();
                if (txsDataTable.getSelectedRows().length > 0) {
                   // tokenUsersThread_btn.set("disabled", false);
                } else {
                   // tokenUsersThread_btn.set("disabled", true);
                }
            });*/

            return {
                ds:txsDataSource,
                dt:txsDataTable
            };
        } catch (e) {
            throw e;
        }

    }();
});
